import {
  getProTodo,
  getProcessed,
  getApply,
  handleTask,
  handleDraft,
  diagramAndInfo,
  currentTasks,
  handleLogs,
  handleTaskclaim,
  getTaskform,
  handleTaskRollback,
  getRollbackList,
  getFlowRecords,
  getNoticeLog,
  getNodeLog,
  getFormLog,
  reSendNoticeMessage,
  recall,
  reject,
  remind,
  turnTask,
  addSignTask,
  delayTask,
  getTaskTimeout,
  getStartFormDetail,
  getProcess,
  handleCompleteWorkItem,
  getNextTaskList,
  skip,
  dispatchWorkItem,
  nextNodeAssignee,
  delegateTask,
  handleWithClaim,
  isExternalForm,
  getExternalForm,
  filledExternalFormInfo,
  historyExternalTaskForm,
  historyExternalProcessForm,
  selectEmployeeList,
  terminateProcessInstance,
  getNextTaskDetail,
  postNextNodeAssignee,
  rollbackToPreNode,
  rollbackToFirstNode,
  getCandidateInfoList,
  queryCandidateTask,
  getCustomTitleList,
  getMustExpress,
  takeBack,
  dealReadDoData,
  getAttachInfoList,
  updateReadFlag,
} from "../pages/flowimplement/flowhandle/server/FlowHandleApi";
// import { detailFormat } from "../pages/flowmanage/formbuilder/nomalFn";

const initData = {
  processData: [],
  processTasks: [],
  processLogs: [],
  processDetailData: {},
  taskformFields: [],
  formName: "任务处理",
  totalCount: 0,
  logsTotalCount: 0,
  tasksTotalCount: 0,
  processedData: {datas: [], totoalCount: 0}, // 流程门户 -> 任务中心 -> 经办任务
  applyData: {datas: [], totoalCount: 0}, // 流程门户 -> 任务中心 -> 我的申请
  flowRecords: [],
  noticeLog: [], // 通知日志
  nodeLog: [], // 节点日志
  formLog: [], // 表单日志
  flowformLog: [], // 流程发起表单
  isExternalForm: false,
  formUrl: '', // 空模版外置表单信息
  exDisplayStyle: '', // 空模版外置表单是否使用审批标准iframe
  exShowAsUrl: '', // 空模版外置表单是否通过url展示
  showExternalFormUrl: '', // 用户填写过的外置表单信息
  displayStyle: '', // 用户填写过的外置表单是否使用审批标准iframe
  showAsUrl: '', // 用户填写过的外置表单是否通过url展示
  listSearchData: [],
  candidateTask: {},
  customTitleList: [],
  mustExpress: true,
  attachInfoList: [], // 附件列表
};

const getNewModel = (model = {}, currentTaskList = []) => {
  const style = {fill: "#fff", stroke: "#f90606"};
  const {nodes} = model;
  if (!nodes) return model;
  const newNodes = nodes.map((item) => {
    if (
      currentTaskList.some(
        (sitem) =>
          sitem === item.id &&
          (item.shape === "UserTask" || item.shape === "AuditTask"),
      )
    ) {
      item.color = "#f90606";
      item.style = style;
      item.shape = "UserActive";
    }
    return item;
  });
  const newModel = {...model, nodes: newNodes};
  return newModel;
};

export default {
  namespace: "FlowHandle",
  state: {
    ...initData,
  },

  effects: {
    * getNoticeLog({payload}, {call, put}) {
      const {errCode, errMsg, errortext, datas = []} = yield call(
        getNoticeLog,
        payload,
      );
      if (`${errCode}` === "0") {
        yield put({
          type: "set/noticeLogs",
          payload: datas,
        });
      }
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * reSendNoticeMessage({payload}, {call, put}) {
      const {taskId, ruNoticeChannelId} = payload;
      const {errCode, errMsg, errortext} = yield call(reSendNoticeMessage, {
        ruNoticeChannelId,
      });
      if (`${errCode}` === "0") {
        yield put({type: "getNoticeLog", payload: {taskId}});
      }
      return {errCode, errMsg: errMsg || errortext};
    },
    * getFormLog({payload}, {call, put}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        getFormLog,
        payload,
      );
      if (`${errCode}` === "0") {
        yield put({
          type: "set/formLogs",
          payload: datas.fields || {},
          fieldData: datas.fieldData || {},
        });
      }
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * getNodeLog({payload}, {call, put}) {
      const {errCode, errMsg, errortext, datas = []} = yield call(
        getNodeLog,
        payload,
      );
      if (`${errCode}` === "0") {
        yield put({type: "set/nodeLogs", payload: datas});
      }
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * getFlowRecords({payload}, {call, put}) {
      const {errCode, errMsg, errortext, datas = []} = yield call(
        getFlowRecords,
        payload,
      );
      if (`${errCode}` === "0") {
        yield put({type: "set/flowRecords", payload: datas});
      }
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * getProTodo({payload}, {call, put}) {
      const {errCode, errMsg, datas = [], totalCount} = yield call(
        getProTodo,
        payload,
      );
      yield put({type: "get/processData", payload: datas, totalCount});
      return {errCode, errMsg, datas};
    },
    * getProProcessed({payload}, {call, put}) {
      const {errCode, errMsg, datas = [], totalCount} = yield call(
        getProcessed,
        payload,
      );
      yield put({type: "get/processData", payload: datas, totalCount});
      return {errCode, errMsg, datas};
    },
    * getProProcessedNew({payload}, {call, put}) {
      const {errCode, errMsg, datas = [], totalCount} = yield call(
        getProcessed,
        payload,
      );
      yield put({type: "set/processedData", payload: {datas, totalCount}});
      return {errCode, errMsg, datas};
    },
    * getProApply({payload}, {call, put}) {
      const {errCode, errMsg, datas = [], totalCount} = yield call(
        getApply,
        payload,
      );
      yield put({type: "get/processData", payload: datas, totalCount});
      return {errCode, errMsg, datas};
    },
    * getProApplyNew({payload}, {call, put}) {
      const {errCode, errMsg, datas = [], totalCount} = yield call(
        getApply,
        payload,
      );
      yield put({type: "set/applyData", payload: {datas, totalCount}});
      return {errCode, errMsg, datas};
    },
    * getProcessDetail({payload}, {call, put}) {
      const {errCode, errMsg, datas = {}} = yield call(
        diagramAndInfo,
        payload,
      );
      const {model, currentTaskList} = datas;
      if (currentTaskList && currentTaskList.length > 0) {
        const newModel = getNewModel(model, currentTaskList);
        datas.model = newModel;
      }
      // const { nodes = []} = model;
      yield put({type: "get/processDetailData", payload: datas});
      return {errCode, errMsg, datas};
    },
    * getCurrentTasks({payload}, {call, put}) {
      const {errCode, errMsg, datas = [], totalCount} = yield call(
        currentTasks,
        payload,
      );
      yield put({type: "get/processTasks", payload: datas, totalCount});
      return {errCode, errMsg, datas};
    },
    * handleLogs({payload}, {call, put}) {
      const {errCode, errMsg, datas = [], totalCount} = yield call(
        handleLogs,
        payload,
      );
      yield put({type: "get/processLogs", payload: datas, totalCount});
      return {errCode, errMsg, datas};
    },
    * handleTask({payload}, {call}) {
      // 处理
      const {errCode, errMsg, errortext, datas} = yield call(
        handleTask,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * handleDraft({payload}, {call}) {
      // 处理
      const {errCode, errMsg, errortext, datas} = yield call(
        handleDraft,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * getTaskform({payload}, {call, put}) {
      const {errCode, errMsg, errortext, datas} = yield call(
        getTaskform,
        payload,
      );
      const {fields = {}, name = ""} = datas || {};
      yield put({type: "get/taskform", payload: fields, formName: name});
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * handleTaskRollback({payload}, {call}) {
      // 退回
      const {errCode, errMsg} = yield call(handleTaskRollback, payload);
      return {errCode, errMsg};
    },
    * getRollbackList({payload}, {call}) {
      // 获取退回环节数据
      const {errCode, errMsg, datas = {}} = yield call(
        getRollbackList,
        payload,
      );
      return {errCode, errMsg, datas};
    },
    * recall({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        recall,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * reject({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        reject,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * remind({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        remind,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * handleTaskclaim({payload}, {call}) {
      const {errCode, errMsg, errortext} = yield call(
        handleTaskclaim,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext};
    },
    * addSignTask({payload}, {call}) {
      const {errCode, errMsg, errortext} = yield call(addSignTask, payload);
      return {errCode, errMsg: errMsg || errortext};
    },
    * turnTask({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        turnTask,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * delayTask({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        delayTask,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * getTaskTimeout({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        getTaskTimeout,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * getStartFormDetail({payload}, {call, put}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        getStartFormDetail,
        payload,
      );
      if (`${errCode}` === "0") {
        yield put({
          type: "set/flowFormLogs",
          payload: datas.fields || {},
          fieldData: datas.fieldData || {},
        });
      }
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * getProcess({payload}, {call, put}) {
      const {errCode, errMsg, datas = {}} = yield call(
        getProcess,
        payload,
      );
      const {model, currentTaskList} = datas;
      if (currentTaskList && currentTaskList.length > 0) {
        const newModel = getNewModel(model, currentTaskList);
        datas.model = newModel;
      }
      // const { nodes = []} = model;
      yield put({type: "get/processDetailData", payload: datas});
      return {errCode, errMsg, datas};
    },
    * handleCompleteWorkItem({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        handleCompleteWorkItem,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * getNextTaskList({payload}, {call, put}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        getNextTaskList,
        payload,
      );
      yield put({type: "get/nextTaskListData", payload: datas.newActivity});
      return {errCode, errMsg: errMsg || errortext, datas};
    },


    * getNextTaskDetail({payload}, {call, put}) {

      // 先清空 避免脏数据
      yield put({type: "get/nextTaskDetailData", payload: []});
      const {errCode, errMsg, errortext, datas = []} = yield call(
        getNextTaskDetail,
        payload,
      );

      yield put({type: "get/nextTaskDetailData", payload: datas});

      return {errCode, errMsg: errMsg || errortext, datas};
    },

    * getCandidateInfoList({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        getCandidateInfoList,
        payload,
      );

      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * postNextNodeAssignee({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        postNextNodeAssignee,
        payload,
      );

      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * skip({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        skip,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * dispatchWorkItem({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        dispatchWorkItem,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * nextNodeAssignee({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        nextNodeAssignee,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * delegateTask({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        delegateTask,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * handleWithClaim({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        handleWithClaim,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * isExternalForm({payload}, {call, put}) {
      const resData = yield call(isExternalForm, payload);
      const {errCode, errMsg, datas = {}, errortext} = resData || {};
      yield put({type: "get/isExternalForm", payload: datas});
      return {errCode, errMsg: errortext || errMsg, datas};
    },
    * getExternalForm({payload}, {call, put}) {
      const {errCode, errMsg, errortext, datas} = yield call(
        getExternalForm,
        payload,
      );
      const {formUrl = "", formId = "", displayStyle = "", showAsUrl = ""} = datas || {};
      yield put({type: "get/getExternalForm", payload: formUrl, formId, displayStyle, showAsUrl});
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * filledExternalFormInfo({payload}, {call, put}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        filledExternalFormInfo,
        payload,
      );
      if (`${errCode}` === "0") {
        yield put({
          type: "set/filledExternalFormInfo",
          payload: datas.formUrl || "",
          displayStyle: datas.displayStyle || "",
          showAsUrl: datas.showAsUrl || "",
          formName: datas.formName || "",
        });
      }
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * historyExternalTaskForm({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        historyExternalTaskForm,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * historyExternalProcessForm({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        historyExternalProcessForm,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * selectEmployeeList({payload}, {call, put, select}) {
      const {pageIndex} = payload;
      const {listSearchData} = yield select(_ => _.FlowHandle);
      const result = yield call(selectEmployeeList, payload);
      const {
        datas: {dataList = [], total},
        errCode,
      } = result;
      if (errCode === 0) {
        if (listSearchData.length < total) {
          yield put({
            type: 'get/listSearchData',
            payload: pageIndex === 1 ? dataList : listSearchData.concat(dataList) || [],
          });
        } else if (listSearchData.length > total) {
          yield put({
            type: 'get/listSearchData',
            payload: dataList,
          });
        }
      }
      return result;
    },
    * terminateProcessInstance({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        terminateProcessInstance,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * rollbackToPreNode({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        rollbackToPreNode,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * rollbackToFirstNode({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        rollbackToFirstNode,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * queryCandidateTask({payload}, {call, put}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        queryCandidateTask,
        payload,
      );
      if (`${errCode}` === "0") {
        yield put({type: "set/candidateTask", payload: datas ?? {}});
      }
      return { errCode, errMsg: errMsg || errortext, datas: datas ?? {}};
    },

    * getCustomTitleList({payload}, {call, put}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        getCustomTitleList,
        payload,
      );
      const customTitleList = [];
      const nameMatch = {
        time: '时间',
        uuid: '其他',
        user: '用户',
      };

      if (`${errCode}` === "0") {

        const allKeys = Object.keys(datas);
        allKeys.map(key => {
          const list = datas[key];

          const tmpList = list.map(item => {
            const {titleCode, titleName} = item;
            return {
              key: titleCode,
              title: titleName,
              checkable: true,
              ...item,
            }
          })

          customTitleList.push({
            title: nameMatch[key] ?? key,
            key,
            checkable: false,
            children: tmpList,
          })

          return key;
        })

        yield put({type: "set/customTitleList", payload: customTitleList ?? {}});
      }
      return {errCode, errMsg: errMsg || errortext, customTitleList};
    },

    * getMustExpress({payload}, {call, put}) {
      const {errCode, errMsg, datas = {mustExpress: '1'}} = yield call(
        getMustExpress,
        payload,
      );
      if (errCode === 0) {
        const {mustExpress = '1'} = datas;
        yield put({type: "set/mustExpress", payload: mustExpress === '1'});
      }
      return {errCode, errMsg, datas};
    },
    * takeBack({payload}, {call}) {
      const {errCode, errMsg, datas = {mustExpress: '1'}} = yield call(
        takeBack,
        payload,
      );

      return {errCode, errMsg, datas};
    },

    * dealReadDoData({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        dealReadDoData,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * getAttachInfoList({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        getAttachInfoList,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },
    * updateReadFlag({payload}, {call}) {
      const {errCode, errMsg, errortext, datas = {}} = yield call(
        updateReadFlag,
        payload,
      );
      return {errCode, errMsg: errMsg || errortext, datas};
    },

  },
  reducers: {
    "set/mustExpress": (state, {payload}) => ({
      ...state,
      mustExpress: payload,
    }),
    "set/customTitleList": (state, {payload}) => ({
      ...state,
      customTitleList: payload,
    }),
    "get/processData": (state, {payload, totalCount}) => ({
      ...state,
      processData: payload,
      totalCount,
    }),
    "set/processedData": (state, {payload}) => ({
      ...state,
      processedData: payload,
    }),
    "set/candidateTask": (state, {payload}) => ({
      ...state,
      candidateTask: payload,
    }),
    "set/applyData": (state, {payload}) => ({
      ...state,
      applyData: payload,
    }),
    "get/processDetailData": (state, {payload}) => ({
      ...state,
      processDetailData: payload,
    }),
    "get/processTasks": (state, {payload, totalCount}) => ({
      ...state,
      processTasks: payload,
      tasksTotalCount: totalCount,
    }),
    "get/processLogs": (state, {payload, totalCount}) => ({
      ...state,
      processLogs: payload,
      logsTotalCount: totalCount,
    }),
    "get/taskform": (state, {payload, formName}) => ({
      ...state,
      taskformFields: payload,
      formName,
    }),
    "set/flowRecords": (state, {payload}) => ({
      ...state,
      flowRecords: payload,
    }),
    "set/noticeLogs": (state, {payload}) => ({
      ...state,
      noticeLog: payload,
    }),
    "set/nodeLogs": (state, {payload}) => ({
      ...state,
      nodeLog: payload,
    }),
    "set/formLogs": (state, {payload, fieldData}) => ({
      ...state,
      formLog: payload,
      fieldData,
    }),
    "set/flowFormLogs": (state, {payload, fieldData}) => ({
      ...state,
      flowformLog: payload,
      fieldData,
    }),
    "get/nextTaskListData": (state, {payload}) => ({
      ...state,
      nextTaskListData: payload,
    }),
    "get/nextTaskDetailData": (state, {payload}) => ({
      ...state,
      nextTaskDetailData: payload,
    }),
    "get/isExternalForm": (state, {payload}) => ({
      ...state,
      isExternalForm: payload,
    }),
    "get/getExternalForm": (state, {payload, formId, displayStyle, showAsUrl}) => ({
      ...state,
      formUrl: payload,
      formId,
      exDisplayStyle: displayStyle,
      exShowAsUrl: showAsUrl,
    }),
    "set/filledExternalFormInfo": (state, {payload, displayStyle, showAsUrl, formName}) => ({
      ...state,
      showExternalFormUrl: payload,
      displayStyle,
      showAsUrl,
      formName,
    }),
    "get/listSearchData": (state, {payload}) => ({
      ...state,
      listSearchData: payload,
    }),
    // "get/attachInfoList": (state, {payload}) => ({
    //   ...state,
    //   attachInfoList: payload,
    // }),
    clearData: () => ({...initData}),
  },
};
